package com.ipt.frm.pw;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.ipartek.fila2.bean.Alumno;
import com.ipartek.fila2.factoria.DAOFactory;
import com.ipartek.fila2.interfaces.InterfaceAlumnoDAO;

/**
 * Servlet implementation class EjemploAjax
 */
public class EjemploAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	private static  DAOFactory fMySQL;
	private static  InterfaceAlumnoDAO aDao;
    
	private static final String TABLE_ALUMNO = "alumno";
	
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EjemploAjax() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/html");
		response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
		
		if(null!=request.getParameter("nombre")){
			out.print(request.getParameter("nombre"));	
		}
		else{
			out.print("hola mundo");
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		fMySQL = DAOFactory.getDAOFactory(DAOFactory.MYSQL);
		aDao = fMySQL.getInterfaceAlumnoDAO();

		
		ArrayList<Alumno> listaAlumnos;
		
		request.setCharacterEncoding(StandardCharsets.UTF_8.toString());
		
		String patron ="%" +request.getParameter("patron")+ "%";
		
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
		response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
		
		String json;
		
		try {
			listaAlumnos = aDao.getAlumnosPorNombre(TABLE_ALUMNO, patron);
			json = new Gson().toJson(listaAlumnos);
			out.print(json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
